<template>
  <div>
    <!-- 日历热力图 -->
    <div style="margin-top:32px;">
      <div ref="calendarChart" style="width:100%;height:280px;"></div>
    </div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="面试类型">
        <el-select v-model="queryForm.intype" placeholder="请选择" clearable>
          <el-option label="模拟面试" value="1"></el-option>
          <el-option label="练习" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="岗位">
        <el-input v-model="queryForm.type" placeholder="请输入岗位" clearable></el-input>
      </el-form-item>
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="queryForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="inid" label="面试ID" width="120" />
      <el-table-column prop="userid" label="用户ID" width="120" :formatter="userFormatter" />
      <el-table-column prop="todate" label="面试时间" width="160" :formatter="dateFormatter" />
      <el-table-column prop="type" label="岗位" :formatter="emptyFormatter" />
      <el-table-column prop="style" label="面试官风格" :formatter="emptyFormatter" />
      <el-table-column prop="scene" label="面试场景" :formatter="emptyFormatter" />
      <el-table-column
        prop="intype"
        label="面试类型"
        :formatter="typeFormatter"
      />
      <el-table-column prop="time" label="面试时长" :formatter="durationFormatter" />
      <el-table-column label="查看报告" width="120">
        <template #default="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleViewDetail(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="pagination.total"
      :page-size="pagination.pageSize"
      :current-page="pagination.page"
      @current-change="handlePageChange"
      style="margin-top: 16px;"
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts'
import { getInterviewRecordList } from '@/api/example/interviewrecord'

export default {
  name: 'InterviewRecord',
  data() {
    return {
      tableData: [],
      allData: [],
      pagination: { page: 1, pageSize: 10, total: 0 },
      userid: this.$store.getters.userId,
      Report: null,
      queryForm: {
        intype: '',
        type: '',
        dateRange: []
      },
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    this.initCalendarChart()
    this.updateCalendarChart()
    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    handleSearch() {
      this.pagination.page = 1 // 重置为第一页
      this.fetchData()
    },
    resetSearch() {
      this.queryForm = {
        intype: '',
        type: '',
        dateRange: []
      }
      this.handleSearch()
    },
    async fetchReport(inid) {
      try {
        const res = await request({
          url: '/api/example/Whu_report/getList',
          method: 'post',
          data: {
            inid: inid,
            page: 1,
            pageSize: 1,
          }
        })
        if (res && res.data && res.data.list && res.data.list.length) {
          const Report = res.data.list[0]
          console.log('报告:', Report)
          this.Report = Report
          return true; // 获取到报告
        }
        return false; // 没有报告
      } catch (error) {
        console.error('获取报告失败:', error)
        return false;
      }
    },
    fetchData() {
      const params = {
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        sidx: 'todate',
        sord: 'desc',
      }

      // 添加查询条件
      if (this.queryForm.intype) {
        params.intype = this.queryForm.intype
      }
      if (this.queryForm.type) {
        params.type = this.queryForm.type
      }
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.todate = [
          new Date(this.queryForm.dateRange[0]).getTime().toString(),
          new Date(this.queryForm.dateRange[1]).getTime().toString()
        ]
      }
      getInterviewRecordList(params).then(res => {
        const data = res.data || {}
        this.tableData = (Array.isArray(data.list) ? data.list : []).map(item => {
          // 处理 JSON 格式的场景数据
          if (item.scene && item.scene.startsWith('[')) {
            try {
              item.scene = JSON.parse(item.scene).join('、')
            } catch (e) {
              console.error('解析场景数据失败:', e)
            }
          }

          // 处理带引号的字符串数据
          ['type', 'style'].forEach(key => {
            if (item[key] && typeof item[key] === 'string' && item[key].startsWith('"')) {
              try {
                item[key] = JSON.parse(item[key])
              } catch (e) {
                console.error(`解析${key}数据失败:`, e)
              }
            }
          })

          // 处理空值显示
          Object.keys(item).forEach(key => {
            if (item[key] === null || item[key] === '') {
              item[key] = '-'
            }
          })

          return item
        })

        if (data.pagination) {
          this.pagination.total = data.pagination.total || 0
          this.pagination.page = data.pagination.currentPage || 1
          this.pagination.pageSize = data.pagination.pageSize || 10
        }
      })
    },
    handleResize() {
    if (this.calendarChart) {
      this.calendarChart.resize();
    }
  },
    handlePageChange(page) {
      this.pagination.page = page
      this.fetchData()
    },
    typeFormatter(row) {
      if (row.intype === '"1"') return '模拟面试'
      if (row.intype === '"0"') return '练习'
      if (row.intype === '-') return '-'
      return row.intype || '-'
    },
    durationFormatter(row, column, cellValue) {
      if (!cellValue || cellValue === '-' || isNaN(cellValue)) return '-'

      const seconds = parseInt(cellValue)
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60

      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0')
      ].join(':')
    },
    async getCalendarData(year) {
      try {
        const params = {
          page: 1,
          pageSize: 10000000,
        };

        const res = await getInterviewRecordList(params);
        const temp = res.data || {};

        this.allData = (Array.isArray(temp.list) ? temp.list : []).map(item => {
          // 处理 JSON 格式的场景数据
          if (item.scene && item.scene.startsWith('[')) {
            try {
              item.scene = JSON.parse(item.scene).join('、')
            } catch (e) {
              console.error('解析场景数据失败:', e)
            }
          }

          // 处理带引号的字符串数据
          ['type', 'style'].forEach(key => {
            if (item[key] && typeof item[key] === 'string' && item[key].startsWith('"')) {
              try {
                item[key] = JSON.parse(item[key])
              } catch (e) {
                console.error(`解析${key}数据失败:`, e)
              }
            }
          })

          // 处理空值显示
          Object.keys(item).forEach(key => {
            if (item[key] === null || item[key] === '') {
              item[key] = '-'
            }
          })
          return item;
        });

        const map = {};
        this.allData.forEach(item => {
          if (item.todate && item.todate !== '-') {
            const date = item.todate.split(' ')[0];
            map[date] = (map[date] || 0) + 1;
          }
        });

        // 生成全年数据...
        const date = new Date(`${year}-01-01`).getTime()
        const end = new Date(`${year + 1}-01-01`).getTime()
        const dayTime = 3600 * 24 * 1000
        const data = []

      for (let time = date; time < end; time += dayTime) {
        const d = new Date(time)
        const dStr = [
          d.getFullYear(),
          String(d.getMonth() + 1).padStart(2, '0'),
          String(d.getDate()).padStart(2, '0')
        ].join('-')
        data.push([dStr, map[dStr] || 0])
      }
        return data;

      } catch (error) {
        console.error('获取热力图数据失败:', error);
        return [];
      }
    },
    initCalendarChart() {
    this.$nextTick(() => {
      if (!this.$refs.calendarChart) return;
      if (!this.calendarChart) {
        this.calendarChart = echarts.init(this.$refs.calendarChart);
        // 添加点击事件
        this.calendarChart.on('click', params => {
          if (params.value && params.value[1] > 0) {
            const date = params.value[0];
            this.queryForm.dateRange = [date, date];
            this.handleSearch();
          }
        });
      }
      this.setCalendarOption();
    });
  },
    updateCalendarChart() {
      if (this.calendarChart) {
        this.setCalendarOption()
      }
    },
    async setCalendarOption() {
  const year = new Date().getFullYear();
  const data = await this.getCalendarData(year);

  // 计算最大值，用于动态调整颜色范围
  const maxValue = Math.max(...data.map(item => item[1]), 10);

  this.calendarChart.setOption({
    title: {
      top: 20,
      left: 'center',
      text: `${year}年面试记录`,
      textStyle: {
        color: '#6d5c36',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      formatter: function(params) {
        const value = params.value[1];
        const date = params.value[0];
        return `
          <div style="font-weight:bold;margin-bottom:5px;">${date}</div>
          <div>面试次数: <span style="font-weight:bold;color:#f8c964">${value}</span></div>
        `;
      }
    },
    visualMap: {
      min: 0,
      max: maxValue,
      type: 'piecewise',
      orient: 'horizontal',
      left: 'center',
      top: 60,
      textStyle: {
        color: '#6d5c36'
      },
      inRange: {
        color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
      },
      pieces: [
        {min: 0, max: 0, color: '#ebedf0', label: '无记录'},
        {min: 1, max: 1, color: '#c6e48b', label: '1次'},
        {min: 2, max: 3, color: '#7bc96f', label: '2-3次'},
        {min: 4, max: 5, color: '#239a3b', label: '4-5次'},
        {min: 5.5, color: '#196127', label: '6次+'}
      ]
    },
    calendar: {
      top: 100,
      left: 30,
      right: 20,
      cellSize: ['auto', 15],
      range: year,
      itemStyle: {
        borderWidth: 1,
        borderColor: '#f7f5f0'
      },
      dayLabel: {
        color: '#6d5c36',
        fontSize: 12
      },
      monthLabel: {
        color: '#6d5c36',
        fontSize: 12,
        nameMap: 'cn'
      },
      yearLabel: {
        show: false
      }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: true,
        formatter: function(params) {
          return params.value[1] > 0 ? params.value[1] : '';
        },
        color: '#fff',
        fontSize: 10
      }
    }
  });
},
    emptyFormatter(row, column, cellValue) {
      return cellValue === null || cellValue === '' ? '-' : cellValue
    },

    dateFormatter(row, column, cellValue) {
      if (!cellValue || cellValue === '-') return '-'
      return cellValue.split(' ')[0] // 只显示日期部分
    },

    userFormatter(row, column, cellValue) {
      if (cellValue && cellValue.includes('/')) {
        return cellValue.split('/')[0] // 只显示用户名部分
      }
      return cellValue || '-'
    },
    async handleViewDetail(row) {
      // 显示加载中状态
      const loading = this.$loading({
        lock: true,
        text: '正在获取分析报告...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        // 使用当前行的inid获取报告
        const success = await this.fetchReport(row.inid)
        if (success && this.Report && this.Report.analysis) {
          window.open(this.Report.analysis, '_blank')
        } else {
          this.$message.warning('该面试记录暂无分析报告')
        }
      } finally {
        loading.close()
      }
    },
  }
}
</script>

<style scoped>
.search-form {
  background: #f7f5f0;
  border-radius: 12px;
  padding: 18px 24px 8px 24px;
  margin-bottom: 18px;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.06);
  border: 1px solid #f0e6d2;
}

.el-form-item__label {
  color: #a68c5a;
  font-weight: 500;
  font-size: 15px;
}

.el-input, .el-select, .el-date-picker {
  border-radius: 6px !important;
  background: #f6f3ea !important;
}

.el-button {
  border-radius: 6px !important;
  font-weight: 500;
}

.el-button--primary {
  background: #f8c964;
  color: #fff;
  border: none;
}

.el-button--primary:hover {
  background: #f3e7c9;
  color: #fff;
}

.el-table {
  background: #f7f5f0;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.06);
  border: 1px solid #f0e6d2;
  margin-bottom: 18px;
}

.el-table th {
  background: #f3e7c9 !important;
  color: #a68c5a !important;
  font-weight: 600;
  font-size: 15px;
}

.el-table td {
  background: #f7f5f0 !important;
  color: #6d5c36;
  font-size: 14px;
}

.el-pagination {
  margin-top: 16px;
  justify-content: center;
}

.el-table .el-button--primary {
  background: #f8c964;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 13px;
}

.el-table .el-button--primary:hover {
  background: #f3e7c9;
  color: #fff;
}

[ref="calendarChart"] {
  background: #f7f5f0;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.06);
  border: 1px solid #f0e6d2;
  padding: 10px;
  transition: all 0.3s;
}

[ref="calendarChart"]:hover {
  box-shadow: 0 4px 12px 0 rgba(200, 180, 120, 0.12);
}
</style>
